package com.lagou.minicat.core;

import com.lagou.minicat.servlet.HttpRequest;
import com.lagou.minicat.servlet.HttpRequestFacade;
import com.lagou.minicat.servlet.HttpResponse;
import com.lagou.minicat.servlet.HttpResponseFacade;
import com.lagou.minicat.util.HttpProtocolUtil;

import javax.servlet.Servlet;
import java.io.IOException;
import java.net.Socket;

public class RequestProcessor implements Runnable {

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            HttpRequest httpRequest = new HttpRequest(socket.getInputStream());
            HttpResponse httpResponse = new HttpResponse(socket.getOutputStream());
            System.out.println("[Request] >> " + httpRequest);

            Servlet servlet = mapper.matchServlet(httpRequest);
            if (servlet != null) {
                httpResponse.output(HttpProtocolUtil.getHttpHeader200(null));
                servlet.service(new HttpRequestFacade(httpRequest), new HttpResponseFacade(httpResponse));
                httpResponse.getWriter().flush();
                httpResponse.getWriter().close();
            } else {
                httpResponse.output(HttpProtocolUtil.getHttpHeader404());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } catch (Error e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException ie) {
                ie.printStackTrace();
            }
        }
    }

}
